package com.bonana.backend.controller;

import com.alibaba.fastjson.JSON;
import com.bonana.core.entity.mybatis.Banner;
import com.bonana.core.form.BannerForm;
import com.bonana.core.result.Response;
import com.bonana.core.result.ResponseCode;
import com.bonana.core.services.BannerService;
import com.bonana.core.utils.FileInfo;
import com.bonana.core.utils.OssUtils;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by Administrator on 2016/7/4.
 */
@Controller
@RequestMapping(value="/banner")
public class BannerController {
    @Autowired
    BannerService bannerService;

    @RequestMapping(value="getBanner", method = RequestMethod.POST)
    @ResponseBody
    public PageInfo getBanner(Integer pgNum, Integer pgSize, Integer type, @RequestParam(required = false) String query) {
        List<Banner> list = bannerService.getBanners(pgNum, pgSize, type, query);
        PageInfo page = new PageInfo(list);
        return page;
    }

    @RequestMapping(value = "queryById")
    @ResponseBody
    public Banner getBannerById(Integer bannerId) {
        return bannerService.getBanerById(bannerId);
    }

    @RequestMapping(value="/list")
    public String init() {
        return "banner/list";
    }

    @RequestMapping(value ="/save", method = RequestMethod.POST)
    @ResponseBody
    public Response saveBanner(BannerForm bannerForm, @RequestParam(required = false) MultipartFile bannerFile, HttpServletRequest request) {
        Banner banner = bannerForm.toBannerModel();
        if (bannerFile!=null) {
            FileInfo fileInfo = OssUtils.putFile(bannerFile);
            banner.setBannerImg(fileInfo.getUrl());
        }

        if (banner.getBannerId() == 0) {
            banner.setBannerId(null);
            bannerService.addBanner(banner);
        } else {
            bannerService.updateBanner(banner);
        }
        return new Response(ResponseCode.SUCC);
    }

    @RequestMapping("/del")
    @ResponseBody
    public Response delBanner(int bannerId) {
        int ret = bannerService.delBanner(bannerId);
        if (ret == 1) {
            return new Response(ResponseCode.SUCC);
        } else {
            return new Response(ResponseCode.ITEM_NOT_FOUND);
        }
    }
}
